package com.interceptor;//package com.southwind.interceptor;

import com.entity.Employee;
import com.service.RoleEmployeeService;
import com.vo.InterceptorAuthorityVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

public class AdminInterceptor implements HandlerInterceptor {

    @Autowired
    private RoleEmployeeService roleEmployeeService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Employee employee = (Employee) request.getSession().getAttribute("employee");
        if(employee == null){
            response.sendRedirect("/login");
        } else {
            //查询该用户所拥有的权限，通过角色查询
            List<InterceptorAuthorityVO> interceptorAuthorityVOS = this.roleEmployeeService.interceptorAuthorityList(employee.getEmployeeId());
            String servletPath = request.getServletPath();
            //判断当前用户是否拥有权限
            for (InterceptorAuthorityVO interceptorAuthorityVO : interceptorAuthorityVOS) {
                String controller = interceptorAuthorityVO.getController();
                if(controller.indexOf(",") > 0){
                    String[] split = controller.split(",");
                    for (String str : split) {
                        if (str.equals(servletPath)) {
                            return true;
                        }
                    }
                } else {
                    if (interceptorAuthorityVO.getController().equals(servletPath)) {
                        return true;
                    }
                }
            }
            response.sendRedirect("/error");
        }
        return false;
    }
}
